#!/usr/bin/perl -w
# 
# CGI-BIN script to show a list of users picked by a
# SELECT expression.
#
# Parameters: table, select, limit
#
use FileTable;
use Counter::CGI;
use CGI::Carp;

$] > 5.008 && binmode(STDOUT, ":utf8"); # set web page output to utf-8
$q = new Counter::CGI;
$table = $q->param('table');
$selection = $q->param('select');
$limit = $q->param('limit');

$file = FileTable::open("db/$table");
warn "Select from $table where $selection limit $limit\n";
@recs = $file->select("$selection LIMIT $limit");

print <<EoF;
content-type: text/html; charset="utf-8"

<html>
<head>
<title>Linux Counter selection $selection from $table</title>
</head>
<body bgcolor=white>
<h1>Some entries from $table</h1>
Selection criteria: $selection<br>
Limit: $limit

<table border>
EoF

if ($table eq "users") {
    @names = qw(email state person.name person.email machines);
    $persons = FileTable::open("db/persons");
    $machines = FileTable::open("db/machines");
} else {
    @names = qw(name placeid);
}
print "<tr><th>Key";
for $name (@names) {
    print "<th>$name";
}
print "\n";
for $rec (@recs) {
    print "<tr><td><a href=\"/cgi-bin/adm/show-user.cgi?key=", $rec->key,
    "&database=real\">", $rec->key, "</a>";

    # Get some junk info....
    if ($table eq "users") {
	$person = $persons->get($rec->key);
	if ($person) {
	    $rec->{'person.name'} = $person->{name};
	    $rec->{'person.email'} = $person->{email};
	} else {
	    $rec->{'person.name'} = "<i>No record</i>";
	}
	@machinelist = $machines->select("owner=?", $rec->key);
	if ($#machinelist == 0) {
	    $rec->{'machines'} = $machinelist[0]->{name};
	} else {
	    $rec->{'machines'} = $#machinelist + 1;
	}
    }
    for $field (@names) {
	print "<td>";
	print $rec->{$field} if defined($rec->{$field});
    }
    # Action fields....
    if ($table eq "users") {
	my $key = $rec->key;
	print "<td>";
	if ($person) {
	    print "<a href=\"/cgi-bin/adm/hide-person.cgi?key=$key\">Hide</a>";
        } elsif ($#machinelist == -1) {
	    print "<a href=\"/cgi-bin/adm/delete-user.cgi?key=$key\">Remove</a>";
	}
    }
    print "\n";
}

print <<EoF;
</table>
</body>
</html>
EoF
